Skip to main content

How to use a more complex data type for typehint in python

Here's an example of how you can use type hints to specify a particular structure for JSON data:

  1. First, let's define a simple structure:
   {
"name": "John Doe",
"age": 30,
"is_student": False
}
  1. Now, let's use type hints to specify this structure:
from typing import Dict, Union, Any
def get_data() -> Dict[str, Union[str, int, bool]]:
# ... function implementation ...
return {"name": "John Doe", "age": 30, "is_student": False}

In the above example:

  •  Dict[str, Union[str, int, bool]] means the function returns a dictionary where keys are strings (str) and values can be either strings, integers, or booleans.
  1. For more complex JSON structures, you can use namedtuples or data classes (Python 3.7+):
from typing import NamedTuple
class Person(NamedTuple):
name: str
age: int
is_student: bool
def get_data() -> Person:
# ... function implementation ...
return Person(name="John Doe", age=30, is_student=False)
  1. For those using Python 3.8 and later, there's an even more elegant way with TypedDict:
from typing import TypedDict
class Person(TypedDict):
name: str
age: int
is_student: bool
def get_data() -> Person:
# ... function implementation ...
return {"name": "John Doe", "age": 30, "is_student": False}

Note: Even with type hints, you'd typically want to validate the actual data structure at runtime if you're receiving this data from untrusted sources. Libraries like Pydantic or Marshmallow can assist with data validation and parsing.